package ru.usu.gv.core;

import javax.swing.ImageIcon;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author spupyrev
 * 03.11.2008
 */
public class ResourceLoader
{
    private static Map<String, ImageIcon> cachedIcons = new HashMap<String, ImageIcon>();

    public static InputStream getResourceAsStream(String path)
    {
        InputStream inputStream = tryLoadResource(path);
        if (inputStream == null)
            System.err.println("Cann't get resource '" + path + "'");

        return inputStream;
    }

    public static ImageIcon loadImage(String path)
    {
        if (!cachedIcons.containsKey(path))
        {
            byte[] byteArray = loadImageAsByteArray(path);
            cachedIcons.put(path, new ImageIcon(byteArray));
        }

        return cachedIcons.get(path);
    }

    private static byte[] loadImageAsByteArray(String path)
    {
        InputStream inputStream = tryLoadResource(path);
        try
        {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] array = new byte[1024];
            int len = inputStream.read(array);
            while (len != -1)
            {
                byteArrayOutputStream.write(array, 0, len);
                len = inputStream.read(array);
            }
            inputStream.close();
            return byteArrayOutputStream.toByteArray();
        }
        catch (IOException e)
        {
            System.err.println("Error during loading image '" + path + "'");
            return null;
        }
    }

    private static InputStream tryLoadResource(String path)
    {
        //System.out.println("Loading resource '" + path + "'");

        InputStream inputStream = ResourceLoader.class.getResourceAsStream(path);
        if (inputStream == null)
        {
            inputStream = ResourceLoader.class.getClassLoader().getResourceAsStream(path);
        }
        if (inputStream == null)
        {
            try
            {
                inputStream = new FileInputStream(new File(path));
            }
            catch (FileNotFoundException e)
            {
            }
        }

        return inputStream;
    }

}
